package com.mine.modules.vm.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mine.common.config.exception.MineBootException;
import com.mine.common.domain.vo.Result;
import com.mine.common.repository.base.Thumbnail;
import com.mine.modules.vm.domain.dto.AssetsFileDto;
import com.mine.modules.vm.domain.query.AssetsFilePageQuery;
import com.mine.modules.vm.entity.VmAssetsFile;
import com.mine.modules.vm.mapper.VmAssetsFileMapper;
import com.mine.modules.vm.service.IThumbnail;
import com.mine.modules.vm.service.IVmAssetsFileService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xujf
 * @since 2024-12-24
 */
@Service
@RequiredArgsConstructor
public class VmAssetsFileServiceImpl extends ServiceImpl<VmAssetsFileMapper, VmAssetsFile> implements IVmAssetsFileService {

    private final IThumbnail thumbnail;

    @Override
    public Result<?> pageList(AssetsFilePageQuery pageQuery) {
        LambdaQueryWrapper<VmAssetsFile> queryWrapper = new LambdaQueryWrapper<>(VmAssetsFile.class);
        if (StringUtils.isNotBlank(pageQuery.getKeywords())) {
            queryWrapper.and(e -> e
                    .like(VmAssetsFile::getName, pageQuery.getKeywords())
                    .or()
                    .like(VmAssetsFile::getContentType, pageQuery.getKeywords())
            );
        }
        if (StringUtils.isNotBlank(pageQuery.getDeviceId())) {
            queryWrapper.eq(VmAssetsFile::getAssetId, pageQuery.getDeviceId());
        }
        Page<VmAssetsFile> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
        return Result.ok(this.page(page, queryWrapper));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> addAssetsFile(AssetsFileDto assetsFile) {
        if (assetsFile == null) {
            return Result.error("参数必填！");
        }
        if (StringUtils.isBlank(assetsFile.getDeviceId()) || assetsFile.getFiles().isEmpty()) {
            return Result.error("参数不完整！");
        }
        String deviceId = assetsFile.getDeviceId();
        try {
            for (MultipartFile file : assetsFile.getFiles()) {
                VmAssetsFile vmAssetsFile = new VmAssetsFile(deviceId, file.getOriginalFilename(), file.getSize(), file.getContentType());
                if (this.save(vmAssetsFile)) {
                    Thumbnail thumbnailEntity = new Thumbnail();;
                    thumbnailEntity.setId(String.format("%s_%s", deviceId, vmAssetsFile.getId()));
                    thumbnailEntity.setSize(file.getSize());
                    thumbnailEntity.setName(file.getOriginalFilename());
                    thumbnailEntity.setContentType(file.getContentType());
                    thumbnailEntity.setUploadDate(new Date(System.currentTimeMillis()));
                    thumbnailEntity.setContent(file.getBytes());
                    thumbnail.save(thumbnailEntity);
                }

//                String fileId = thumbnail.uploadFile(file);
//                if (StringUtils.isNotBlank(fileId)) {
//                    VmAssetsFile vmAssetsFile = new VmAssetsFile(deviceId, file.getOriginalFilename(), file.getSize(), file.getContentType());
//                    this.save(vmAssetsFile);
//                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new MineBootException("操作失败！");
        }
        return Result.ok("添加成功！");
    }

    @Override
    public Result<?> deleteById(String deviceId, String fileId) {
        if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(fileId)) {
            return Result.error("参数不完整！");
        }
        try {
            if (this.removeById(fileId)) {
                thumbnail.deleteById(String.format("%s_%s", deviceId, fileId));
            }
            return Result.OK("删除成功！");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Override
    public Result<?> deleteBatch(String deviceId, String fileIds) {
        if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(fileIds)) {
            return Result.error("参数不完整！");
        }
        String[] ids = fileIds.split(",");
        for (String id : ids) {
            this.deleteById(deviceId, id);
        }
        return Result.ok("操作成功！");
    }

    @Override
    public ResponseEntity<byte[]> download(String deviceId, String fileId) {
        if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(fileId)) {
            throw new MineBootException("参数不完整！");
        }
        try {
            Thumbnail thumb = thumbnail.findById(String.format("%s_%s", deviceId, fileId));
            if (thumb.getContent() == null) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
            String fileName = URLEncoder.encode(thumb.getName(), "UTF-8");
            byte[] fileData = thumb.getContent();
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
            headers.add(HttpHeaders.CONTENT_TYPE, thumb.getContentType());
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileData);

//            Thumbnail thumb = thumbnail.findById(fileId);
//            String fileName = URLEncoder.encode(thumb.getName(), "UTF-8");
//            byte[] fileData = thumbnail.downloadFile(fileId);
//            return ResponseEntity.ok()
//                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
//                    .body(fileData);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new MineBootException("下载失败！");
        }
    }

}
